import axios from 'axios';

class MUtil {

  request(param) {
    return new Promise((resolve, reject) => {
      axios({
        method: param.method || 'get',
        url: param.url || '',
        responseType: param.dataType || 'json',
        params: param.data || null,
      })
        .then(res => {
          // res.data.status为1时表示用户名或者密码错误
          if (0 === res.data.status) {
            typeof resolve === 'function' && resolve(res.data, res.data.msg);
          } else if (10 === res.data.status) {
            this.doLogin();
          } else {
            typeof reject === 'function' && reject(res.data || res.data.msg);
          }
        })
        .catch(err => {
          reject(err || res.data || res.data.msg);
        });
    });
  }
  // 获取url参数
  getUrlParam(name) {
    let queryString = window.location.search.split('?')[1] || '',
      regx = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
      result = queryString.match(regx);

    return result ? decodeURIComponent(result[2]) : null;
  }
  // 成功提示
  successTips(successMsg) {
    alert(successMsg || '操作成功');
  }
  // 错误提示
  errorTips(errMsg) {
    alert(errMsg || '好像哪里不对劲啊');
  }
  // 去登陆
  doLogin() {
    window.location.href = `/login?redirect=${encodeURIComponent(window.location.pathname)}`;
  }

  setStorage(key, value) {
    let dataType = typeof value;
    if (dataType === 'object') {
      localStorage.setItem(key, JSON.stringify(value));
    }
    else if (['number', 'string', 'boolean'].indexOf(dataType)) { // 基础类型
      localStorage.setItem(key, value);
    }
    else {
      alert('该类型不能用于本地存储');
    }
  }

  getStorage(key) {
    let value = localStorage.getItem(key);
    if (value) {
      return JSON.parse(value);
    } else return '';
  }

  removeStorage(key) {
    localStorage.removeItem(name);
  }
}

export default MUtil;